package com.wanggsx.library.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.wanggsx.library.util.fun.download.DownloadCallback;

/** --------------------版本更新开始 ---------------------------- */
public class UtilsAppVersion {
    //apk下载路径
    private static String downurl;
    //是否强制更新
    private static boolean mIsForceUpdate = false;
    //请求文件读写权限计数
    private static int count = 0;
    //新版本的版本号
    private static String newVersionStr;
    //当前Activity
    private static Activity mActivityForNewVersion;
    //更新对话框
    private static AlertDialog mDialogUpdate;
    //请求读写权限时的请求码
    private static final int REQ_WRITE_PERMISSION = 100100;
    //返回是否需要强制更新，当用户已经同意并且开始下载时，则不再强制下载
    public static boolean getIsForceUpdate() {
        return mIsForceUpdate;
    }

    public static AlertDialog getmDialogUpdate() {
        return mDialogUpdate;
    }

    /**
     * 响应返回按钮事件
     * */
    public static boolean isShowingUpdateDialogWhenKeyBack(){
        if (mDialogUpdate!=null){
            return true;
        }else{
            return false;
        }
    }

    public static void dismissDialog(){
        if (mDialogUpdate!=null){
            mDialogUpdate.dismiss();
            mDialogUpdate = null;
        }
    }

    //此方法需要在Activity的onRequestPermissionsResult方法中主动调用
    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (requestCode == REQ_WRITE_PERMISSION) {
            //跳转通讯录
            downApk();
        }
    }

    /**
     * 此方法为更新版本调用
     * 调用注意：
     * 1、在activity的onRequestPermissionsResult方法中调用UtilsApp的onRequestPermissionsResult方法；
     * 2、在activity的onBackPressed方法中调用getIsForceUpdate方法，如果返回true，则不响应返回事件；返回false，则可以响应返回事件；
     * 3、在activity的onDestory方法中调用dismissDialog方法以销毁对话框
     * 4、在activity的onActivityResult方法中调用UtilsInstallApk工具类中的onActivityResult方法
     * 5、在res/xml中添加文件network_config.xml
     *    内容：
     *      <network-security-config>
     *          <base-config cleartextTrafficPermitted="true" />
     *      </network-security-config>
     *    在manifest.xml文件中添加属性：
     *    android:networkSecurityConfig="@xml/network_config"
     *  6、在manifest.xml文件中添加fileProvider：
     *        <provider
     *             android:name="android.support.v4.content.FileProvider"
     *             android:authorities="你的包名.fileProvider"
     *             android:exported="false"
     *             android:grantUriPermissions="true">
     *             <meta-data
     *                 android:name="android.support.FILE_PROVIDER_PATHS"
     *                 android:resource="@xml/rc_file_path" />
     *         </provider>
     *
     *    其中rc_file_path文件的内容为：
     * <paths>
     *     <external-path
     *             name="rc_external_path"
     *             path="."/>
     *     <root-path
     *             name="rc_root_path"
     *             path=""/>
     *     <cache-path
     *             name="cache_path"
     *             path="."/>
     *     <file-path
     *             name="file_path"
     *             path="."/>
     *     <external-cache-path
     *             name="external_cache_path"
     *             path="."/>
     *     <external-files-path
     *             name="external_files_path"
     *             path="."/>
     * </paths>
     *
     * */
    public static void checkNewVersionShowDialogAndDownloadAndInstall(Activity context,String newVerName,
                                                                      boolean isForceUpdate,String apkUrl
            ,String updateText){
        mActivityForNewVersion = context;
        if (mActivityForNewVersion == null)return;
        newVersionStr = newVerName;
        mIsForceUpdate = isForceUpdate;
        downurl = apkUrl;
        count = 0;
        if (checkVersion(getAppVersionName(mActivityForNewVersion.getApplication().getPackageName()),newVersionStr)){
            showUpdateDialog(mActivityForNewVersion,newVersionStr,updateText);
        }
    }

    /** 版本更新对话框 */
    private static void showUpdateDialog(Context context, String newVerionName ,String updateText) {
        if (mDialogUpdate != null) {
            mDialogUpdate.dismiss();
            mDialogUpdate = null;
        }
        //4、下载完毕后启动对话框
        mDialogUpdate = new AlertDialog.Builder(context).create();
        mDialogUpdate.setCanceledOnTouchOutside(false);
        mDialogUpdate.setTitle("温馨提示");
        mDialogUpdate.setMessage("您有新版本(V" + newVerionName + ")要下载安装。请确认是否安装？ \n" + updateText);
        mDialogUpdate.setButton(AlertDialog.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialogUpdate.dismiss();
                downApk();
                UtilsToast.showLong("开始下载,请稍等");
            }
        });
        if (!mIsForceUpdate){
            mDialogUpdate.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDialogUpdate.dismiss();
                }
            });
        }
        mDialogUpdate.show();
        if (mIsForceUpdate){
            mDialogUpdate.setCancelable(false);
        }
    }

    private static void download(String urlNewApk){
        //用户已经通过了文件读写权限，且已经开始下载apk，则强制下载状态改为false
        mIsForceUpdate = false;
        final String strFile = UtilsFile.getAutoFileDirectory() + newVersionStr +".apk";
        UtilsHttps.download(urlNewApk, strFile, true, new DownloadCallback() {
            @Override
            public void onProcess(int finishLen, int maxLen) {

            }

            @Override
            public void onFinish(boolean isSuccess,final String fileName) {
                UtilsToast.showLong("下载完毕");
                mActivityForNewVersion.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        install(mActivityForNewVersion,fileName);
                    }
                });
            }
        });
    }

    public static void downApk(){
        if (checkAndRequestWritePermission(mActivityForNewVersion)){
            download(downurl);
        }
    }

    /** 检查或请求文件写权限 */
    public static boolean checkAndRequestWritePermission(Activity activity) {
        if (activity==null)return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasPermission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                if (count>=1 && !mIsForceUpdate){}else{
                    activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQ_WRITE_PERMISSION);
                }
                count ++;
                return false;
            }
        }
        return true;
    }

    /** --------------------版本更新结束 ---------------------------- */
    public static String getAppVersionName(final String packageName) {
        if (isSpace(packageName)) return "";
        try {
            PackageManager pm = Utils.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static int getAppVersionCode(final String packageName) {
        if (isSpace(packageName)) return -1;
        try {
            PackageManager pm = Utils.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean install(Activity con, String filePath) {
        UtilsInstallApk.install(con, filePath);
        return true;
    }

    /***
     * 判断两个版本是否不一致，是否需要更新
     */
    public static boolean checkVersion(String thisVersion,String newVersion){
        if (thisVersion==null || newVersion==null || !thisVersion.contains(".") || !newVersion.contains(".")){
            return false;
        }
        String[] strOlds = thisVersion.replace(".","_").split("_");
        String[] strNews = newVersion.replace(".","_").split("_");
        try {
            if (Integer.parseInt(strOlds[0]) < Integer.parseInt(strNews[0])){
                return true;
            }else if (Integer.parseInt(strOlds[0]) == Integer.parseInt(strNews[0])){
                if (Integer.parseInt(strOlds[1]) < Integer.parseInt(strNews[1])){
                    return true;
                }else if (Integer.parseInt(strOlds[1]) == Integer.parseInt(strNews[1])){
                    if (Integer.parseInt(strOlds[2]) < Integer.parseInt(strNews[2])){
                        return true;
                    }else if (Integer.parseInt(strOlds[2]) == Integer.parseInt(strNews[2])){
                        if (strOlds.length>=4 && strNews.length >= 4){
                            if (Integer.parseInt(strOlds[3]) < Integer.parseInt(strNews[3])){
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
        }catch (Exception e){
            return false;
        }
        return false;
    }

}
